#include <iostream>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <unistd.h>

using namespace std;

void SetNonblock(int fd)
{
    int fl = fcntl(fd, F_GETFL); //获取文件描述符的模式标记
    if(fl == -1)
    {
        perror("SetNonblock");
        exit(errno);
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK); //设置为非阻塞模式
    // fcntl(fd, F_SETFL, fl &~ O_NONBLOCK); //如果想重新设置为阻塞模式，就要将该位关闭
    cout << "set" << fd << "nonblock done!" << endl;
}

int main()
{
    char buffer[1024];
    SetNonblock(0);
    while(true)
    { 
        cout << "Place Enter: ";
        fflush(stdout);
        ssize_t n = read(0, buffer, sizeof(buffer)-1);
        if(n > 0) //表示成功读取到了数据
        {
            buffer[n-1] = 0;
            cout << "echo: " << buffer << endl;
        }
        else if(n == 0) //表示对端关闭或是读取到文件结束EOF
        {
            cout << "EOF" << endl;
            break;
        }
        else
        {
            cout << endl;
            if(errno == EWOULDBLOCK) //表示数据没有就绪 EWOULDBLOCK == EAGAIN == 11
            {
                cout << "fd 0 not ready! try again!" << endl;
                //do other thing
                //......
                sleep(1);
            }
            else //表示读取错误
            {
                cerr << strerror(errno) << endl;
                break;
            }
        }
    }
}